package com.app.configuration.web.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.app.util.common.Constants;
import com.app.util.common.HandlerResult;
import com.app.util.common.ObjUtil;
import com.app.util.common.RequestUtil;
import com.app.util.common.ResponseUtil;
import com.app.util.common.SpringUtil;
import com.app.util.database.mybatis.Page;
import com.app.util.database.mybatis.QueryType;
import com.suncnpap.base.common.GlobaUser;
import com.suncnpap.reader.model.Reader;
import com.suncnpap.system.model.Admin;
import com.suncnpap.system.model.GroupType;
import com.suncnpap.system.model.Menu;
import com.suncnpap.system.service.GroupTypeService;
import com.suncnpap.system.service.MenuService;

/**
 * 用户登录，权限认证的拦截
 * @author chenl
 *
 */

@Configuration
@WebFilter(urlPatterns = "/*", filterName = "httpSessionUserFilter")
public class HttpSessionUserFilter implements Filter{

	private static final Logger log = Logger.getLogger(HttpSessionUserFilter.class);
	
	
	
	String loginUrl;				//登录地址
	
	String logoutUrl;				//登出地址
	
	String httpSessionExcludePath;			//不进行httpSession验证的目录地址
	
	String httpSessionExcludeUrl;			//不进行httpSession验证的url
	
	String userRightExcludePath;			//不进行权限拦截的路径
	
	String userRightExcludeUrl;				//不进行权限拦截的url
	
	
	
    private Environment environment;
	
    @Autowired
    private MenuService menuService;
    
    @Autowired
    private GroupTypeService groupTypeService;
    
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub		
		environment = SpringUtil.getBean(Environment.class,filterConfig.getServletContext());
		
		loginUrl = environment.getProperty("httpSessionFilter.loginUrl","");
		logoutUrl = environment.getProperty("httpSessionFilter.logoutUrl","");
		httpSessionExcludePath = environment.getProperty("httpSessionFilter.excludePath","");
		httpSessionExcludeUrl = environment.getProperty("httpSessionFilter.excludeUrl","");
		userRightExcludePath = environment.getProperty("userRightFilter.excludePath","");
		userRightExcludeUrl = environment.getProperty("userRightFilter.excludeUrl","");
		
		log.debug("初始化httpSessionUserFilter成功!!!");
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		
		
		HttpServletRequest request = (HttpServletRequest)req;
		
		HttpServletResponse response = (HttpServletResponse)res;
				
		// 获取 servlet上下文
//        ServletContext sc = request.getSession().getServletContext();
//        // 获取 spring 容器
//        AbstractApplicationContext cxt = (AbstractApplicationContext) WebApplicationContextUtils.getWebApplicationContext(sc);
//        if(cxt != null && cxt.getBean("menuService") != null && menuService == null){
//            // 取出 userInfoService
//        	menuService = (MenuService) cxt.getBean("menuService");
//        }
//        if(cxt != null && cxt.getBean("groupTypeService") != null && groupTypeService == null){
//            // 取出 userInfoService
//        	groupTypeService = (GroupTypeService) cxt.getBean("groupTypeService");
//        }
//        
//        Object[] object = GlobaUser.getUser(request.getHeader("token"));
//        Page page = new Page();
//		Map<String,Menu> map = new HashMap<String, Menu>();
//		Map<String,Menu> allMap = new HashMap<String, Menu>();
//        if(object!=null){
//        	if((object[0]+"").equals("reader")){
////        		Reader reader = (Reader) object[1];
//        		
//        		page = new Page();
//		    	page.addQueryAnd("strNature", "user");
//        		List<Menu> allMenuList = menuService.getList(page, "");
//    	    	allMap = ObjUtil.listToObjMapByField(allMenuList, "strUrl");
//    	    	map = allMap;
//        	}else{
//        		Admin admin = (Admin) object[1];
//        		String strGroupTypeId = admin!=null?admin.getStrGroupTypeId():"";
//            	if(admin!=null &&!admin.getStrUser().equals(Constants.INIT_USER_ID)){
//        			if(strGroupTypeId!=null && !strGroupTypeId.equals("")){
//        				GroupType groupType = groupTypeService.findById(strGroupTypeId);
//        				String range = "";
//						if(groupType!=null){
//							range = groupType.getStrMenuRange();
//						}
//        				
//        				page = new Page();
//        		    	page.addQueryAnd("strId", QueryType.MarkINREVERSE, ObjUtil.strToSql(range));
//        		    	List<Menu> menuList = menuService.getList(page, "");
//        		    	map = ObjUtil.listToObjMapByField(menuList, "strUrl");
//        			}
//        	    	page = new Page();
////        	    	page.addQueryAnd("strId", QueryType.MarkINREVERSE, ObjUtil.strToSql(strGroupTypeId));
//        	    	List<Menu> allMenuList = menuService.getList(page, "");
//        	    	allMap = ObjUtil.listToObjMapByField(allMenuList, "strUrl");
//        	    	
//        		}
//        	}
//        }
//		
//		
//		String contextPath = request.getContextPath();
//		String uri = request.getRequestURI();
//		
//		if(uri.indexOf(contextPath) == 0){
//			uri = uri.substring(contextPath.length());
//		}
//		if(uri.startsWith("//")) uri = uri.substring(1,uri.length());
////		if(uri.endsWith("/")) uri = uri.substring(0,uri.length()-1);
//		if(uri.lastIndexOf("/")>-1 && uri.lastIndexOf("/")!=0){
//			uri = uri.substring(0,uri.lastIndexOf("/"));
//		}
//    	
//    	if(allMap!=null && allMap.containsKey(uri)){
//    		if(map!=null && map.containsKey(uri)){
//    			chain.doFilter(req, res);
//    		}else{
//    			HandlerResult result = new HandlerResult();
//    			result.setCode(1);
//    			result.setMessage("没有权限");
//    			ResponseUtil.writeJson(result, response);
//    		}
//    	}else{
    		chain.doFilter(req, res);
//    	}
    	
//		//当前请求的url
//		String uri = request.getRequestURI();
//		String contextPath = request.getContextPath();
//		
//		if(uri.indexOf(contextPath) == 0){
//			uri = uri.substring(contextPath.length());
//		}
//		System.out.println("uri================"+uri);
		
		
//		if(uri.equals("") || uri.startsWith(loginUrl)) {
			
//		}else {
//			
//			//验证是否在忽略的路径中,默认为否，
//			boolean isValid = false;
//			
//			//独立地址验证
//			if(httpSessionExcludeUrl != null && !httpSessionExcludeUrl.equals("")) {
//				String[] excludeUrlArr = httpSessionExcludeUrl.split(",");
//				for(int i=0;i<excludeUrlArr.length;i++) {
//					String tempUrl = excludeUrlArr[i];
//					if(uri.equals(tempUrl)) {
//						isValid = true;		//表示在忽略中
//						break;
//					}
//				}
//			}
//			
//			
//			//访问路径的验证
//			if(isValid == false && httpSessionExcludePath != null && !httpSessionExcludePath.equals("")) {
//				String[] excludePathArr = httpSessionExcludePath.split(",");
//				for(int i=0;i<excludePathArr.length;i++) {
//					String tempPath = excludePathArr[i];		//配置的路劲如/upload/**
//					tempPath = tempPath.replace("**", "");
//					
//					//当前的访问路径如 /upload/aaa/
//					if(uri.startsWith(tempPath)) {
//						isValid = true;
//					}
//				}
//			}
//			
//			
//			if(isValid) {		//当是不需要进行登录认证的时候，直接执行结束
//				
//				//log.debug("当前请求的地址为："+uri+";;非必须登录,请求通过");
//				chain.doFilter(req, response);
//				
//			}else {		//需要登录认证
//				
//				//log.debug("当前请求的地址为："+uri+";;必须登录,请求处理开始");
//				//判断当前用户是否已经登录
//				
//				Admin user = null;//Globa.getUser();
//				if(user == null) {
//					//log.debug("当前请求的地址为："+uri+";;必须登录,请求处理结束--未通过");
//					
//					
//					if(RequestUtil.isAjax((HttpServletRequest)request)){	//是ajax请求
//			        	
//			        	Map<String,Object> map = new HashMap<String,Object>();
//			        	map.put("globa_sessionTimeOut", "-1");
//			        	map.put("tip","<font color='red'><b>登录超时，请重新登录系统</b></font>");
//			        	ResponseUtil.writeJson(map, (HttpServletResponse)response);
//					}else {	//非ajax请求则直接跳转到登录页面
//						response.sendRedirect(request.getContextPath() + loginUrl);
//					}
//					
//					return;
//				}else {					
//					//log.debug("当前请求的地址为："+uri+";;必须登录,请求处理结束--通过");
//					chain.doFilter(req, res);	//继续执行
//				}
//			}
//		}
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		log.debug("销毁httpSessionUserFilter成功!!!");
	}

	
	
}
